// SPDX-License-Identifier: GPL-2.0-or-later

#include <Snake/Field/RectShapeField.hpp>

#include <cstdint>
#include <string>

#include <Snake/Field/AField.hpp>

#include <Snake/Position.hpp>
#include <Snake/Field/Tile.hpp>

#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

RectShapeField::RectShapeField(uint8_t size, const sf::FloatRect& rect) : AField(size)
{
	//Allocation of matrix of sf::RectangleShape
	this->cells = new sf::RectangleShape*[size];

	for(size_t i = 0; i < size; ++i)
	{
		this->cells[i] = new sf::RectangleShape[size];
	}

	this->erase();

	//Fill matrix of sf::RectangleShape with data
	const float cellSize = rect.width / size;

	for(size_t i = 0; i < this->size; ++i)
	{
		for(size_t j = 0; j < this->size; ++j)
		{
			sf::RectangleShape& cell = this->cells[i][j];

			float left = rect.left + (i * cellSize);
			float top = rect.top + (j * cellSize);

			cell.setSize({cellSize, cellSize});
			cell.setPosition({left, top});
			cell.setOrigin(cellSize / 2, cellSize / 2); // For normal rotaion
		}
	}
}

RectShapeField::~RectShapeField()
{
	for(size_t i = 0; i < this->size; ++i)
	{
		delete[] this->cells[i];
	}

	delete[] this->cells;
}
void RectShapeField::setTile(const Position& position, const Tile& tile)
{
	sf::Color color;

	switch(tile.type)
	{
		case Tile::Type::Background:
			color = sf::Color::Black;
			break;
		case Tile::Type::Apple:
			color = sf::Color::Red;
			break;
		case Tile::Type::SHead:
			color = sf::Color::Yellow;
			break;
		case Tile::Type::SBody:
			color = sf::Color::Green;
			break;
		case Tile::Type::STurnedBody:
			color = sf::Color::Green;
			break;
		case Tile::Type::STail:
			color = sf::Color::Green;
			break;
	}
	this->cells[position.x][position.y].setRotation((float)tile.rotation);
	this->cells[position.x][position.y].setFillColor(color);
}

void RectShapeField::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	for(size_t i = 0; i < this->size; ++i)
	{
		for(size_t j = 0; j < this->size; ++j)
		{
			target.draw(this->cells[i][j]);
		}
	}
}
